package com.godme.concurrent.pattern;

import javax.swing.event.ChangeEvent;

public class BalkingPattern {

    public static class ContentManager {
        private String content;
        private boolean changed;


        public void change(String content){
            this.content = content;
            changed = true;
        }

        public synchronized void save(){
            if(changed){
                doSave();
                changed = false;
            } else {
                System.err.println(Thread.currentThread().getName() + "\t已保存");
            }
        }
        public void doSave(){
            System.err.println(Thread.currentThread().getName() + "\t保存文件: " + content);
        }
    }

    static class ChangeThread extends Thread{
        private final ContentManager contentManager;

        public ChangeThread(String name, ContentManager contentManager){
            super(name);
            this.contentManager = contentManager;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                contentManager.change("第\t"+i+"\t次修改");
                try{
                    sleep(500);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    static class SaveThread extends Thread{

        private ContentManager contentManager;
        public SaveThread(String name, ContentManager contentManager){
            super(name);
            this.contentManager = contentManager;
        }

        @Override
        public void run() {
            while(true){
                contentManager.save();
                try {
                    sleep(500);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        ContentManager contentManager = new ContentManager();
        for (int i = 0; i < 3; i++) {
            new ChangeThread("change-"+i, contentManager).start();
        }

        for (int i = 0; i < 2; i++) {
            new SaveThread("save-"+i, contentManager).start();
        }
    }


}
